//
//  NewsViewController.m
//  DailyNews
//
//  Created by 于跃隆 on 2018/12/21.
//  Copyright © 2018年 于跃隆. All rights reserved.
//

#import "NewsViewController.h"
#import "NewsTableViewCell.h"
#import "HttpHandle.h"
#import "MJRefresh.h"
#import "NewsDetailViewController.h"
#import "CollectionHandle.h"

@interface NewsViewController ()<UITableViewDataSource , UITableViewDelegate>
@property (nonatomic , strong) UITableView *tbv;
@property (nonatomic , strong) NSMutableArray *datasource;

@end

@implementation NewsViewController

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[CollectionHandle sharedDBManager] fetchAll];
    [self.tbv reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.datasource = [[NSMutableArray alloc] init];
    
    [self.view addSubview:self.tbv];
    [self.tbv registerNib:[UINib nibWithNibName:@"NewsTableViewCell" bundle:nil] forCellReuseIdentifier:@"NewsCell"];
    
    self.navigationItem.title = @"新闻头条";
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(AddClick)];
    
    [self loadData];
    [self MJRefreshHeader];
    [self MJRefreshFooter];
    
}
-(void)AddClick{
    HttpHandle *http = [[HttpHandle alloc] init];
    [[CollectionHandle sharedDBManager] insertModel:http];
    [self.tbv reloadData];
}
-(void)loadData{
    // 1.创建一个网络路径
    
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://v.juhe.cn/toutiao/index"]];
    
    // 2.创建一个网络请求，分别设置请求方法、请求参数
    
    NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:url];
    
    request.HTTPMethod = @"POST";
    
    NSString *Pathstring = @"67968aeebf1f4e3b6170f7217b6f3cdb";
    
    NSString *args = [NSString stringWithFormat:@"key=%@",Pathstring];
    
    request.HTTPBody = [args dataUsingEncoding:NSUTF8StringEncoding];
    
    // 3.获得会话对象
    
    NSURLSession *session = [NSURLSession sharedSession];
    
    // 4.根据会话对象，创建一个Task任务
    
    NSURLSessionDataTask *sessionDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        NSLog(@"从服务器获取到数据");
        
        /*
         
         对从服务器获取到的数据data进行相应的处理.
         
         */
        
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableLeaves) error:nil];
        NSLog(@"%@",dict[@"result"][@"data"]);
        
        
        for (NSDictionary *dic in dict[@"result"][@"data"]) {
            HttpHandle *http = [[HttpHandle alloc] init];
            [http setValuesForKeysWithDictionary:dic];
            [self.datasource addObject:http];
        }
        [self.tbv reloadData];
    }];
    
    //5.最后一步，执行任务，(resume也是继续执行)。
    
    [sessionDataTask resume];
}
-(void)MJRefreshHeader{
    
    // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
    self.tbv.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        //进行数据刷新操作
        [self loadData];
        
        
        [self.tbv.mj_header endRefreshing];
    }];

    // 马上进入刷新状态
    [self.tbv.mj_header beginRefreshing];
    
    [self.tbv reloadData];
}
-(void)MJRefreshFooter{
    self.tbv.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        //进行数据刷新操作
        [self loadData];
        
        
        [self.tbv.mj_footer endRefreshing];
    }];
    
    // 马上进入刷新状态
    [self.tbv.mj_footer beginRefreshing];
    [self.tbv reloadData];
}

- (UITableView *)tbv{
    if (!_tbv) {
        _tbv = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
        _tbv.dataSource = self;
        _tbv.delegate = self;
    }
    return _tbv;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _datasource.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NewsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsCell"];
    if (self.datasource.count>0) {
        HttpHandle *http = _datasource[indexPath.row];
        [cell setValueForCellModel:http];
        [[CollectionHandle sharedDBManager] insertModel:http];
    }
    
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 120;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    NewsDetailViewController *detail = [[NewsDetailViewController alloc] init];
    HttpHandle *http = _datasource[indexPath.row];
    detail.pathUrl = http.url;
    detail.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:detail animated:YES];
}


@end
